﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TekaMUD.Engine.IO
{
	/// <summary>
	/// Stores the currently open IO channels of the server.
	/// </summary>
	public class ChannelManager
	{
		private static List<BaseChannel> _channelDB;
		private static Object SyncRoot = new object();

		static ChannelManager()
		{
			_channelDB = new List<BaseChannel>();
		}

		public static void RegisterNewChannel(BaseChannel c)
		{
			lock (SyncRoot)
			{
				if(_channelDB.Contains(c))
					throw new Exception("Channel already registered.");

				_channelDB.Add(c);
			}
		}

		public static void RemoveDeadChannels()
		{
			List<BaseChannel> tmpList = new List<BaseChannel>();

			lock (SyncRoot)
			{
				foreach (BaseChannel c in _channelDB)
					if (c.Status == ChannelStatusEnum.Closed || c.Status == ChannelStatusEnum.Timeout)
						tmpList.Add(c);

				foreach (BaseChannel c in tmpList)
				{
					c.Dispose();
					_channelDB.Remove(c);
				}
			}
		}

		public static void GetChannelStatistics(out int total, out int opened, out int closed, out int other)
		{
			total = opened = other = closed = 0;

			lock (SyncRoot)
			{
				total = _channelDB.Count;

				foreach (BaseChannel c in _channelDB)
					switch (c.Status)
					{
						case ChannelStatusEnum.Opened:
							opened++;
							break;

						case ChannelStatusEnum.Closed:
							closed++;
							break;

						default:
							other++;
							break;
					}
			}
		}

		public static void CloseChannel(StdioChannel chan)
		{
			lock (SyncRoot)
			{
				_channelDB.Remove(chan);

				if(chan.Player != null)
					PlayerManager.Remove(chan.Player);
			}
		}
	}
}